package com.ls.lserp.modules.setting.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.FileUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.utils.SystemPath;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.setting.entity.Ognization;
import com.ls.lserp.modules.setting.service.CustomerService;
import com.ls.lserp.modules.sys.entity.Dict;
import com.ls.lserp.modules.sys.utils.DictUtils;

import groovy.util.ResourceException;

/**
 * @ClassName: CustomerController
 * @Description: 客户信息数据
 * 
 * @author 
 * @date 2017年1月9日 下午18:40:00
 *
 */

@Controller
@RequestMapping(value = "${adminPath}/custemer/message")
public class CustomerController extends BaseController{
	
	//客户类别
	public static final Long OGNIZATION_TYPE= 5L;
	
	@Autowired
	// 保存 编辑 删除 方法
	private CustomerService customerService;
	
	@ModelAttribute
	public Ognization get(@RequestParam(required=false) String id) {
		
		// 判断id是否为空
		if (StringUtils.isNotBlank(id)){
			
			// 执行查询语句 查询基本信息
			return customerService.getOgnizationData(Long.parseLong(id));
		}else{
			
			// 若为空，实例化
			return new Ognization();
		}
	}
	
	/**
	 * 进入一览页面
	 * @param ognization
	 * @param model
	 * @return
	 */
	@RequiresPermissions("custemer:message:view")
	@RequestMapping(value = {"list",""})
	public String list(Ognization ognization, HttpServletRequest request, HttpServletResponse response, Model model) {

		// 返回页面地址
	    return "modules/setting/customer";
	}
	
	@RequiresPermissions("custemer:message:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(Ognization ognization, HttpServletRequest request, HttpServletResponse response, Model model)
			throws ResourceException {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		FileUtils filUtils = new FileUtils();
		DateFormat dateForamat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "ognization");
		
		// 画面取得的检索项目
		String pCustomerName = ognization.getOgnizationName();
		String pCateCd = ognization.getOgnizationCategoryCd();
		// 拼接字符串供分页使用
		String searchParam = "&ognizationName=" + pCustomerName + "&ognizationCategoryCd=" + pCateCd;
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam);
		
		//账户类型（1、平台账户；2、店铺账户；3、加工厂账户；4、供货商账户；5、客户；）
		ognization.setOgnizationType(OGNIZATION_TYPE);
		ognization.setCurrentUser(ognization.getCurrentUser());
		// 查询一览页面数据
		Page<Ognization> page = customerService.findList(new Page<Ognization>(request, response), ognization);
		
		// 读取系统路径
		String basePath = SystemPath.getClassPath();
		String tempFilePath = "//"+basePath + "templates//demoHtml//customer.txt";
		// 读取文件生成字符串
		String ognizationHtml = readTxtFile(tempFilePath);
		String strHtml = "";
		int pageNo = 0;
		if (!"".equals(ognizationHtml)) {
			for (int i = 0; i < page.getList().size(); i++) {
				ognizationHtml = filUtils.readFileToHtml(tempFilePath);
				// 画面No
				pageNo = (page.getPageNo() - 1) * page.getPageSize() + (i + 1);
				ognizationHtml = ognizationHtml.replace("pageNo", "" + pageNo);
				
				// 客户名
				String strCtx = request.getContextPath()+Global.getAdminPath();
				ognizationHtml = ognizationHtml.replace("ognizationName", StringUtils.checkStringNull(page.getList().get(i).getOgnizationName()));
				String ognizationline = "\"popup('900px','584px','" + strCtx + "/custemer/message/show?id=" 
						+ page.getList().get(i).getId() + "')\"";
				// 客户名popup
				ognizationHtml = ognizationHtml.replace("ognizationIdPopup", ognizationline);
				// 客户简称
				ognizationHtml = ognizationHtml.replace("ognizationSimpleName", StringUtils.checkStringNull(page.getList().get(i).getOgnizationSimpleName()));
				// 客户分类
				ognizationHtml = ognizationHtml.replace("ognizationCategoryCd", StringUtils.checkStringNull(DictUtils.getDictName(page.getList().get(i).getOgnizationCategoryCd())));
				// 客户级别
				ognizationHtml = ognizationHtml.replace("ognizationLevelCd", StringUtils.checkStringNull(DictUtils.getDictName(page.getList().get(i).getOgnizationLevelCd())));
				// 客户地址
				ognizationHtml = ognizationHtml.replace("ognizationAddress", StringUtils.checkStringNull(page.getList().get(i).getOgnizationAddress()));
				// 联系人
				ognizationHtml = ognizationHtml.replace("contactPerson", StringUtils.checkStringNull(page.getList().get(i).getContactPerson()));
				// 联系电话
				ognizationHtml = ognizationHtml.replace("contactPhone", StringUtils.checkStringNull(page.getList().get(i).getContactPhone()));
				// 邮编
				ognizationHtml = ognizationHtml.replace("ognizationZipCode", StringUtils.checkStringNull(page.getList().get(i).getOgnizationZipCode()));
				// 创建人
				ognizationHtml = ognizationHtml.replace("createAllName", 
						StringUtils.checkStringNull(page.getList().get(i).getCreateBy().getFirstName())
						+StringUtils.checkStringNull(page.getList().get(i).getCreateBy().getLastName()));
				// 创建日期
				dateForamat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				Date createDate = page.getList().get(i).getCreateDate();
				ognizationHtml = ognizationHtml.replace("createDate", StringUtils.checkStringNull(dateForamat.format(createDate)));
				strHtml += ognizationHtml;
			}
		}
		listMap.put("ognization", strHtml);
		listMap.put("page", page.getHtml());
		// ajax返回结果
		return renderString(response, listMap);
	}

	/**
	 * 
	 * 功能：Java读取txt文件的内容 1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
	 * 3：读取到输入流后，需要读取生成字节流
	 * 
	 * @param filePath
	 * @return html
	 */
	public String readTxtFile(String filePath) {
		String strHtml = "";
		try {
			String encoding = "UTF-8";
			File file = new File(filePath);
			// 判断文件是否存在
			if (file.isFile()) {
				InputStreamReader read = new InputStreamReader(
						// 考虑到编码格式
						new FileInputStream(file), encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				String lingText = null;
				while ((lingText = bufferedReader.readLine()) != null) {
					strHtml += lingText;
				}
				read.close();
			} else {

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strHtml;
	}
	
	/**
     * 进入查看页面
     * @param ognization
     * @param model
     * @return
     */
    @RequiresPermissions("custemer:message:view")
    @RequestMapping(value = "show")
    public String show(Ognization ognization, Model model) {
    	
        // 将查询结果赋值mvc model层返回jsp页面
        model.addAttribute("ognization", ognization);
        
        // 返回页面地址
        return "modules/setting/customerShow";
    }
    
  /**
    * 逻辑删除
    * @param ognization
    * @param model
    * @return
    */
   @RequiresPermissions("custemer:message:edit")
   @RequestMapping(value = "delete")
   @ResponseBody
   public String delete(Ognization ognization, HttpServletRequest request, Model model, HttpServletResponse response) throws Exception {
	   Map<Object, Object> listMap = new HashMap<Object, Object>();
	   try {
		   //删除客户
		   customerService.delete(ognization);
		   listMap.put("delFlag" , "true");
		} catch (Exception e) {
			listMap.put("delFlag" , "false");
			logger.error (e.getMessage (), e);
		}
       
       // 返回页面地址
       return renderString(response,listMap);
   }
    
	/**
	 * 进入编辑页面
	 * @param ognization
	 * @param model
	 * @return
	 */
	@RequiresPermissions("custemer:message:edit")
	@RequestMapping(value = "form")
	public String form(Ognization ognization,RedirectAttributes redirectAttributes, Model model,HttpSession session) {
		
		if(ognization.getId()==null){
			ognization.preInsert();
		}
		
		ognization.setSelBrandList(customerService.selBrandList());
		
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("ognization", ognization);
		
		// 返回页面地址
		return "modules/setting/customerCreate";
	}
	
	/**
	 * 保存信息
	 * @param ognization
	 * @param request
	 * @param model
	 * @param response
	 * @return
	 * @throws ResourceException 
	 */
	@RequiresPermissions("custemer:message:edit")
	@RequestMapping(value = "save")
	@ResponseBody
	public String save(Ognization ognization, HttpServletRequest request, Model model, HttpServletResponse response , HttpSession session) throws ResourceException {
		
		// 判断id是否为null （判断新建或修改）
		if(ognization.getId()!=null){
			// 编辑数据
			// 判断数据是否删除
			Ognization ognizationNew = get(ognization.getId().toString());
			// 判断数据是否删除
            if(ognizationNew==null || BaseEntity.DEL_FLAG_DELETE.equals(ognizationNew.getDeleteFlag())){
            	// 返回提示信息
            	return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
            }
			
            // 排他处理
		    if((ognization.getVersion()==get(ognization.getId().toString()).getVersion()) &&
		       (ognization.getBankVersion()==get(ognization.getId().toString()).getBankVersion())){
		    	
		    	// 版本号加1
		    	ognization.setVersion(ognization.getVersion()+1);
		    	ognization.setBankVersion(ognization.getBankVersion()+1);
		    }else{
		    	
		    	// 返回提示信息
		        return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
		    }
		}
			
			ognization.setOgnizationType(OGNIZATION_TYPE);
			
		    // 保存数据
			customerService.saveCustomer(ognization);
			
			// 保存成功返回提示信息
	        return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName( "customer_save_success")));
	}
	
	/**
     * 联动返回城市
     * @param code
     * @param response
     * @return
     */
    @RequiresPermissions("custemer:message:view")
    @RequestMapping(value = "city")
    @ResponseBody
    public String city(String code,HttpServletResponse response ) {
    	
    	/*前台返回国家code值写入code，调用方法查询code值下的城市列表*/
        List<Dict> cityList=DictUtils.getDictList(code); 
        
        return renderString(response, cityList);
       
    }
}
